import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';

@Injectable()
export class PollingService implements OnModuleInit, OnModuleDestroy {
  private count = 0;
  private interval: NodeJS.Timeout;
  private intervalMs = 3000; // Default 3 seconds

  onModuleInit() {
    // Auto increment count every 3 seconds
    this.startInterval();
  }

  onModuleDestroy() {
    // Cleanup interval
    if (this.interval) {
      clearInterval(this.interval);
    }
  }

  private startInterval() {
    if (this.interval) {
      clearInterval(this.interval);
    }
    this.interval = setInterval(() => {
      this.increment();
    }, this.intervalMs);
  }

  getCount() {
    return { count: this.count };
  }

  increment() {
    this.count += 1;
    return { count: this.count };
  }

  reset() {
    this.count = 0;
    return { count: this.count };
  }

  setInterval(intervalMs: number) {
    this.intervalMs = intervalMs;
    this.startInterval();
    return { message: `Interval set to ${intervalMs}ms` };
  }
}
